<?php

namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\facade\Session;
use think\facade\Validate;

class Account extends BaseController
{
    // 登录表单
    public function login()
    {
        return view('/account/login');
    }

    // 登录验证
    public function dologin()
    {
        $user = Session::get('user');
        $user && die(json_encode(['code' => 1, 'msg' => '你已登录']));
        $phone = input('post.phone');
        $pwd = input('post.pwd');
        // 简单验证
        $rule = [
            'phone|手机' => 'require',
            'pwd|密码' => 'require',
        ];
        $validate = Validate::rule($rule);
        !$validate->check(compact('phone', 'pwd')) && die(json_encode(['code' => 1, 'msg' => $validate->getError()]));

        // 检查用户
        $user = Db::table('users')->where('phone', $phone)->find();
        !$user && die(json_encode(['code' => 1, 'msg' => '用户不存在']));
        !password_verify($pwd, $user['pwd']) && die(json_encode(['code' => 1, 'msg' => '密码错误']));
        !session_id() && session_start();
        Session::set('user', $user);
        echo json_encode(['code' => 0, 'msg' => '登录成功']);
    }

    // 资料
    public function profile()
    {
        $user = Session::get('user');
        !$user && die('<p style="text-align:center">请先登录</p>');
        $id = $user['id'] ?? 0;
        $user = Db::table('users')->where('id', $id)->find();
        !$user && die('<p style="text-align:center">用户不存在</p>');
        return view('/account/profile', ['user' => $user]);
    }

    // 修改资料
    public function doprofile()
    {
        !$this->request->checkToken() && die(json_encode(['code' => 1, 'msg' => '令牌数据无效']));
        $user = Session::get('user');
        !$user && die(json_encode(['code' => 1, 'msg' => '请先登录']));
        $name = input('post.name');
        $avatar = input('post.avatar');
        $id = $user['id'] ?? 0;
        $user = Db::table('users')->where('id', $id)->find();
        !$user && die(json_encode(['code' => 1, 'msg' => '用户不存在']));
        Db::table('users')->where('id', $user['id'])->update(compact('name', 'avatar'));
        $avatar && Db::table('files')->where('path', $avatar)->update(['status' => 0]);
        echo json_encode(['code' => 0, 'msg' => '修改成功']);
    }
}
